<template>
  <div>
    <el-row>
      <el-form ref="articleFormRef" :model="form" :rules="rules">
        <el-form-item hidden>
          <el-input v-model="form.articleId" hidden />
          <el-input v-model="form.status" hidden />
          <el-input v-model="form.thumbnail" hidden />
          <el-input v-model="form.source" hidden />
        </el-form-item>
        <el-col :xs="{span: 24}" :sm="{span: 24}" :md="{span: 18}" :lg="{span: 18}" :xl="{span: 18}" class="p-r-10">
          <el-card>
            <el-form-item prop="title">
              <el-input v-model="form.title" placeholder="文章标题" />
            </el-form-item>
            <el-form-item prop="summary">
              <el-input
                v-model="form.summary"
                type="textarea"
                placeholder="文章摘要"
                :rows="2"
              />
            </el-form-item>
            <el-form-item>
              <el-card>
                <el-form-item class="m-b-20">
                  <label class="m-r-10">抓取链接：</label>
                  <el-autocomplete
                    v-model="grep.grep_url"
                    size="small"
                    style="width:80%"
                    :fetch-suggestions="queryGrep"
                    placeholder="url,编码格式"
                    @select="defineGrep"
                  />
                </el-form-item>
                <el-form-item class="m-b-20">
                  <label class="m-r-10">爬取规则：</label>
                  <el-input v-model="grep.grep_url_define" size="small" style="width:80%" placeholder="替换位,起始值,结束值" />
                </el-form-item>
                <el-row>
                  <el-tabs>
                    <el-tab-pane label="爬取标题规则">
                      <el-input v-model="grep.grep_title_define" placeholder="爬取规则：正则表达式">
                        <template slot="prepend"><i class="el-icon-edit-outline" /></template>
                      </el-input>
                    </el-tab-pane>
                    <el-tab-pane label="爬取缩略图规则">
                      <el-input v-model="grep.grep_image_define" placeholder="爬取规则：正则表达式">
                        <template slot="prepend"><i class="el-icon-picture-outline" /></template>
                      </el-input>
                    </el-tab-pane>
                    <el-tab-pane label="爬取下载路径规则">
                      <el-input v-model="grep.grep_download_define" placeholder="爬取规则：正则表达式">
                        <template slot="prepend"><i class="el-icon-paperclip" /></template>
                      </el-input>
                    </el-tab-pane>
                    <el-tab-pane label="爬取大文本规则">
                      <el-input v-model="grep.grep_content_define" placeholder="爬取规则：标签标识[属性名:属性值]">
                        <template slot="prepend"><i class="el-icon-tickets" /></template>
                      </el-input>
                    </el-tab-pane>
                  </el-tabs>
                </el-row>
              </el-card>
            </el-form-item>
            <el-form-item prop="content">
              <tinymce-editor ref="tinymce" v-model="form.content" :height="380" @input="renderHtml" @close="onClose" />
            </el-form-item>
            <el-form-item>
              <el-col :span="10">
                <el-input v-model="video_url" size="small" placeholder="URL地址转码" />
              </el-col>
              <el-col :span="2" style="text-align: center;">
                <el-button type="primary" icon="el-icon-refresh" circle @click="translateURL" />
              </el-col>
              <el-col :span="10">
                <el-input v-model="video_url_encode" size="small" placeholder="转码后URL地址" />
              </el-col>
            </el-form-item>
          </el-card>
        </el-col>
        <el-col :xs="{span: 24}" :sm="{span: 24}" :md="{span: 6}" :lg="{span: 6}" :xl="{span: 6}">
          <el-card :body-style="{ padding: '0px', textAlign: 'center' }">
            <el-image style="height:300px" :src="getImageSrc(form.thumbnail)" alt="点击更换图片" fit="fill" @click="changeThumbnail">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline" @click="changeThumbnail" />
              </div>
            </el-image>
          </el-card>
          <el-divider />
          <el-card>
            <el-row>
              <el-col :span="24">
                <el-form-item prop="channel">
                  <label class="m-r-10">文章栏目</label>
                  <el-select v-model="form.channel" size="small">
                    <el-option
                      v-for="item in optionOfChannel"
                      :key="item.dictCode"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="direction">
                  <label class="m-r-10">显示方向</label>
                  <el-select v-model="form.direction" size="small">
                    <el-option
                      v-for="item in optionOfDirection"
                      :key="item.dictCode"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="open">
                  <label class="m-r-10">访问权限</label>
                  <el-radio v-for="item in optionOfPermission" :key="item.dictCode" v-model="form.open" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="memberLevel">
                  <label class="m-r-10">访问等级</label>
                  <el-select v-model="form.memberGrowth" size="small">
                    <el-option
                      v-for="item in optionOfMemberGrowth"
                      :key="'member_growth_' + item.id"
                      :label="item.name"
                      :value="item.growthPoint"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="crypto">
                  <label class="m-r-10">加密</label>
                  <el-radio v-for="item in optionOfCrypto" :key="item.dictCode" v-model="form.crypto" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
                </el-form-item>
              </el-col>
              <el-col v-if="form.crypto === '0'" :span="24">
                <el-form-item prop="salt">
                  <label class="m-r-10">分享码</label>
                  <el-input v-model="form.salt" size="small" class="w-50" placeholder="请输入分享码" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="weight">
                  <label class="m-r-10">排序</label>
                  <el-input-number v-model="form.weight" size="small" :min="1" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <label class="m-r-10">标签</label>
              <el-tag
                v-for="tag in optionOfTag"
                :key="tag"
                size="small"
                closable
                :disable-transitions="false"
                class="m-l-5"
                @close="handleTagDelete(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="inputTagVisible"
                ref="saveTagInput"
                v-model="inputTagValue"
                size="small"
                class="input-new-tag"
                @keyup.enter.native="handleTagConfirm"
                @blur="handleTagConfirm"
              />
              <el-button v-if="!inputTagVisible" size="small" class="button-new-tag" icon="el-icon-plus" @click="handleAddTag" />
            </el-form-item>
            <el-form-item>
              <el-tag type="success" class="m-r-5">⋅ 阅读 {{ form.views }} ⋅</el-tag>
              <el-tag type="success" class="m-r-5">⋅ 收藏 {{ form.favors }} ⋅</el-tag>
              <el-tag type="success">⋅ 评论 {{ form.views }} ⋅</el-tag>
            </el-form-item>
            <el-row type="flex" justify="center">
              <el-button type="warning" :disabled="grep.grep_url===undefined" @click="onSubmit('0')">预 览</el-button>
              <el-button type="primary" :disabled="grep.grep_url===undefined" @click="onSubmit('1')">抓取并保存</el-button>
            </el-row>
          </el-card>
        </el-col>
      </el-form>
    </el-row>

    <el-dialog title="文章缩略图" :modal="false" :visible.sync="openThumbnailDialog">
      <image-cropper ref="thumbnailCrop" :fixed-size="false" :upload-url="uploadThumbnailFinalUrl" @onSuccess="setThumbnail" />
    </el-dialog>
  </div>
</template>

<script>
import { grepSelectData, manageLoad, crawDefineGrep } from '@/api/tool/craw'
import { memberLevelList } from '@/api/system/member'
import Auth from '@/utils/auth'

export default {
  name: 'CrawlForm',
  data() {
    return {
      redirect: undefined,
      form: {
        articleId: undefined,
        status: '2',
        thumbnail: '',
        source: 'crawl',
        title: undefined,
        summary: undefined,
        content: undefined,
        html: undefined,
        open: '0',
        crypto: '1',
        memberGrowth: 0,
        salt: undefined,
        weight: 0,
        channel: undefined,
        direction: undefined,
        tags: '',
        views: 0,
        favors: 0,
        comments: 0
      },
      grep: {
        grep_url: undefined,
        grep_url_define: undefined,
        grep_title_define: undefined,
        grep_image_define: undefined,
        grep_download_define: undefined,
        grep_content_define: undefined
      },
      grepData: [],
      uploadThumbnailFinalUrl: `${process.env.VUE_APP_MODULE_BLOG_API}/api/blog/manage/uploadThumbnailFinal`,
      video_url: '',
      video_url_encode: '',
      rules: {},
      optionOfPermission: [],
      optionOfMemberGrowth: [],
      optionOfCrypto: [],
      optionOfChannel: [],
      optionOfDirection: [],
      optionOfTag: [],
      inputTagValue: undefined,
      inputTagVisible: false,
      openThumbnailDialog: false
    }
  },
  watch: {
    optionOfTag(value) {
      this.form.tags = this.optionOfTag.join(',')
    }
  },
  methods: {
    init(articleId) {
      // 加载下拉菜单
      this.getDictData()
      if (articleId) {
        this.form.articleId = articleId
        this.$nextTick(() => {
          // 加载表单数据
          this.loadForm()
        })
      }
    },
    getDictData() {
      const that = this
      this.$http.all([this.$dictGroup('blog_article_open'),
          memberLevelList(),
          this.$dictGroup('sys_yes_no'),
          this.$dictGroup('blog_article_channel'),
          this.$dictGroup('blog_article_direction')
        ]).then(this.$http.spread(function(permission, growth, crypto, channel, direction) {
        that.optionOfPermission = permission
        that.optionOfMemberGrowth = growth
        that.optionOfCrypto = crypto
        that.optionOfChannel = channel
        that.optionOfDirection = direction
      }))

      grepSelectData().then(response => {
        const data = response.param
        if (data.length > 0) {
          data.forEach(value => {
            this.grepData.push({
              value: value
            })
          })
        }
      }).catch(e => {})
    },
    getImageSrc(value) {
      return this.$api.getImageSrc(value)
    },
    loadForm() {
      if (this.form.articleId) {
        manageLoad({ 'id': this.form.articleId }).then(response => {
          this.form = this.$api.objectUpdate(this.form, response.param)
          if (this.form.tags) {
            this.optionOfTag = this.form.tags.split(',')
          }
          // 加载tinymce插件
          this.$refs.tinymce.update('')
          this.$refs.tinymce.update(this.form.content)
        }).catch(() => {})
      }
    },
    queryGrep(queryString, cb) {
      const restaurants = this.grepData
      const results = (queryString && queryString.value) ? restaurants.filter(item => {
        return item.value.toLowerCase().indexOf(queryString.value.toLowerCase()) === 0
      }) : restaurants
      cb(results)
    },
    defineGrep(item) {
      if (item) {
        this.grep.grep_url = item.value
      }
      if (this.grep.grep_url && this.grep.grep_url.length > 5) {
        crawDefineGrep({ key: this.grep.grep_url }).then(response => {
          this.grep.grep_title_define = response.param.grep_title_define
          this.grep.grep_image_define = response.param.grep_image_define
          this.grep.grep_download_define = response.param.grep_download_define
          this.grep.grep_content_define = response.param.grep_content_define
        }).catch(e => {})
      }
    },
    changeThumbnail() {
      this.openThumbnailDialog = true
      this.$nextTick(() => {
        let avatarUrl
        if (this.form.thumbnail) {
          avatarUrl = this.$store.getters.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/public/file/preview/` + this.form.thumbnail
        } else {
          avatarUrl = ''
        }
        this.$refs.thumbnailCrop.init(avatarUrl)
      })
    },
    setThumbnail(avatarId) {
      this.form.thumbnail = avatarId
      this.openThumbnailDialog = false
    },
    translateURL() {
      if (this.video_url) {
        this.video_url_encode = encodeURI(this.video_url)
      }
    },
    handleAddTag() {
      this.inputTagVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleTagConfirm() {
      const inputValue = this.inputTagValue
      if (inputValue) {
        this.optionOfTag.push(inputValue)
      }
      this.inputTagVisible = false
      this.inputTagValue = ''
    },
    handleTagDelete(tag) {
      this.optionOfTag.splice(this.optionOfTag.indexOf(tag), 1)
    },
    renderHtml(render) {
      this.form.html = render
    },
    onSubmit(type) {
      let url = `${process.env.VUE_APP_MODULE_BLOG_API}/api/blog/manage/crawl/crawler`
      if (type === '0') {
        url = `${process.env.VUE_APP_MODULE_BLOG_API}/api/blog/manage/crawl/crawler?preview=1`
      } else {
        if (this.form.channel === undefined) {
          this.$modal.msgWarning('请选择栏目')
          return false
        }

        // 判断是否加密
        if (this.form.crypto === '0') {
          if (!this.form.salt) {
            this.$modal.msgWarning('请输入分享码')
            return false
          }
          this.form.content = Auth.Encrypt(this.form.content)
          if (this.form.summary) {
            this.form.summary = Auth.Encrypt(this.form.summary)
          }
        }
      }

      const param = Object.assign(this.form, this.grep)
      this.$http.post(url, param).then(response => {
        this.$modal.msgSuccess(response.msg)
        this.form = this.$api.objectUpdate(this.form, response.param)
        this.$refs.tinymce.update(this.form.content)
      }).catch(() => {})
    },
    onClose() {
      this.form = {
        articleId: undefined,
        status: '2',
        thumbnail: '',
        source: 'crawl',
        title: undefined,
        summary: undefined,
        content: undefined,
        html: undefined,
        open: '0',
        crypto: '1',
        memberGrowth: 0,
        salt: undefined,
        weight: 0,
        channel: undefined,
        direction: undefined,
        tags: '',
        views: 0,
        favors: 0,
        comments: 0
      }
      this.$refs.tinymce.update('')
      this.grep = {
        grep_url: undefined,
        grep_url_define: undefined,
        grep_title_define: undefined,
        grep_image_define: undefined,
        grep_download_define: undefined,
        grep_content_define: undefined
      }
      this.video_url = ''
      this.video_url_encode = ''
      this.tags = []
      this.inputTagValue = undefined
      this.inputTagVisible = false
      this.openThumbnailDialog = false
    }
  }
}
</script>
